package com.nzf.vote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nzf.vote.entity.User;
import com.nzf.vote.mapper.UserMapper;
import com.nzf.vote.mapper.UserVoteMapper;
import com.nzf.vote.mapper.VoteMapper;
import com.nzf.vote.model.vo.Results;
import com.nzf.vote.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nzf
 * @since 2022-07-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    VoteMapper voteMapper;
    @Autowired
    UserVoteMapper userVoteMapper;
    @Override
    public User login(String username, String password) {
        return userMapper.login(username,password);
    }

    @Override
    public Results insertUser(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);
        user.setCreateTime(LocalDateTime.now());
        if(user1==null){
            if(user.getStatus()==null){
                user.setStatus(2);
            }
            int insert = userMapper.insert(user);
            return Results.success(insert);
        }else{
            return new Results(500,"用户名已存在");
        }
    }

    @Override
    public int deleteUser(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        userVoteMapper.delete(queryWrapper);
        voteMapper.delete(queryWrapper);
        return userMapper.deleteById(id);
    }
}
